package com.lepu.app.usercenter;

import java.util.HashMap;
import java.util.Map;

import lib.share.login.UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;

public class UserModifyNameActivity extends BaseFragmentActivity implements
		AsyncRequest {

	private static final String REQUEST_SAVE_NICKNAME = "request_save_nickname";
	private static final String REQUEST_THIRD_CHECK_NICKNAME = "request_third_check_nickname";
	private static final String REQUEST_THIRD_LOGIN_BOND = "request_third_login_bond";

	private static final int MSG_SAVE_SUCESS = 10;
	private static final int MSG_SAVE_FAIL = 11;

	private boolean mThirdLoginModify = false;

	@Override
	@SuppressLint("InflateParams")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_modify_name_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	// ===========================================================================================

	private void init() {

		String nickName = "";
		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			mThirdLoginModify = data.getBoolean("ThirdLoginModifyNickName",
					false);
			nickName = data.getString("NickName");
		}
		
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		contentEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(15) });

		if(mThirdLoginModify)
		{
			contentEditText.setText(nickName);
		}else{
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			contentEditText.setText(loginInfo.NickName);
		}

		TextView closeTextView = (TextView) findViewById(R.id.closeTextView);
		closeTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finishAnim(R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);
			}
		});

		TextView saveTextView = (TextView) findViewById(R.id.saveTextView);
		saveTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				saveContent();
			}
		});
	}

	private void saveContent() {
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		String content = contentEditText.getText().toString().trim();
		if (TextUtils.isEmpty(content)) {
			UIHelper.showToast(this, "昵称不能为空，请输入您的昵称");
			return;
		}

		if (mThirdLoginModify) {
			requestThirdCheckNickName();
		} else {
			requestSaveNickName();
		}
	}

	private void requestSaveNickName() {
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		
		String content = contentEditText.getText().toString().trim();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("NickName", content);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post(Setting.getUpdateNickNameUrl(), map, null, this,
				REQUEST_SAVE_NICKNAME, true);
	}

	private void requestThirdCheckNickName() {
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		String content = contentEditText.getText().toString().trim();
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("NickName", content);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog(false);
		ApiClient.http_post_main(Setting.getCheckNickNameIsAvailable(), map, null, this,
				REQUEST_THIRD_CHECK_NICKNAME, true);
	}
	
	private void requestThirdLoginBond() {
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		String content = contentEditText.getText().toString().trim();
		
		EditText yaoQingCodeEditText = (EditText) findViewById(R.id.yaoQingCodeEditText);
		String yaoQingCode = yaoQingCodeEditText.getText().toString().trim();

		LoginActivity loginActivity = (LoginActivity) AppManager.getAppManager().getActivity(LoginActivity.class);
		UserInfo info = loginActivity.getThirdUserInfo();
		
		UserCenterUtil.thirdpartyBind(this, this, REQUEST_THIRD_LOGIN_BOND,content,yaoQingCode, info.userId,
				loginActivity.getThirdLoginType(), info.userToken,
				String.valueOf(info.userExpiresTime));
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_SAVE_SUCESS:

				hideProgressDialog();
				finishAnim(R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);

				UserInfoActivity.getInstance().updateUserInfo();

				break;
			case MSG_SAVE_FAIL:
				hideProgressDialog();
				finishAnim(R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);

				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_SAVE_NICKNAME)) {
			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {

				EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				loginInfo.NickName = contentEditText.getText().toString()
						.trim();

				LoginInfo.saveLoginInfo(this, loginInfo);

				mHandler.sendEmptyMessage(MSG_SAVE_SUCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_SAVE_FAIL);
			}
		}else if (object.equals(REQUEST_THIRD_CHECK_NICKNAME)) {
			String result = (String) data;
			int isAvailable = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");
				isAvailable = obj2.optInt("IsAvailable");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			if(isAvailable == 1){
				requestThirdLoginBond();
			}else{
				UIHelper.showToast(this, "此昵称已被占用，请更换昵称");
				//服务端提示用户	message
				hideProgressDialog();
			}
		}else if (object.equals(REQUEST_THIRD_LOGIN_BOND)) {
			hideProgressDialog();
			
			String result = (String) data;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				dataObject = (JSONObject) obj1.get("DetailInfo");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			LoginInfo loginInfo = LoginInfo.parseLoginInfo(dataObject
					.toString());
			LoginInfo.saveLoginInfo(this, loginInfo);
			
//			finishAnim(R.anim.lib_push_down_up_in,
//					R.anim.lib_push_down_up_out);
//			AppManager.getAppManager().finishActivity(LoginActivity.class);
			Intent intent = new Intent(this,MainTabActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_SAVE_NICKNAME)) {
			mHandler.sendEmptyMessage(MSG_SAVE_FAIL);
		}else if (object.equals(REQUEST_THIRD_CHECK_NICKNAME)) {
			hideProgressDialog();
		}else if (object.equals(REQUEST_THIRD_LOGIN_BOND)) {
			hideProgressDialog();
		}
	}
}
